<template>
  <!-- 设备管理 -->
  <div id="financeSettleEditDiv">
      <div style="width: 100%;height: 100%;">
          <el-container class="container">
            <el-steps :active="active" finish-status="success" simple style="background-color: rgba(135, 206, 235, 0.45);height: 30px;width: 34%;margin-top: 10px;">
              <el-step title="选择申请条码" ></el-step>
              <el-step title="收费项目结算" ></el-step>
            </el-steps>
            <el-card style="margin-top: 10px;width: 100%;height: calc(100% - 66px);">
              <div v-if="active === 1" style="height: 100%;">
                <vxe-toolbar perfect>
                  <template #buttons>
                    <el-form :model="searchPersonForm"  class="form-input-m" style="height: 30px" label-width="80px" :inline="true">
                      <el-form-item label="关键字查询" clearable>
                        <vxe-input  type="text"  v-model="searchPersonForm.searchValue" clearable @blur="findReqNoList"></vxe-input>
                      </el-form-item>
                      <el-form-item label="申请日期" clearable>
                        <vxe-input v-model="searchPersonForm.startTime" type="date" placeholder="起始日期" clearable transfer/>
                        <div>-</div>
                        <vxe-input v-model="searchPersonForm.endTime" type="date" placeholder="截至日期" clearable transfer/>
                      </el-form-item>
                      <el-form-item>
                        <vxe-button type="text" class="button-blue" content="查询" @click="findReqNoList"></vxe-button>
                      </el-form-item>
                    </el-form>
                  </template>
                </vxe-toolbar>
                <div class="tableBody" style="height: calc(100% - 36px - 34px)">
                  <vxe-table ref="personTableRef" class="mytable-scrollbar dialogTable" border height="auto" align="center" :data="reqNoList" :loading="ploading" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                    <vxe-column title="序号" width="80">
                      <template #default="{ row, rowIndex, column }">
                        <span>{{ rowIndex + 1 }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="reqNo" title="条码号"></vxe-column>
                    <vxe-column field="patNo" title="病历号"></vxe-column>
                    <vxe-column field="patNa" title="患者姓名"></vxe-column>
                    <vxe-column field="reqPurpose" title="检测项目"></vxe-column>
                  </vxe-table>
                </div>
                <div style="float: right;margin-right: 40px;">
                  <vxe-button type="text" class="button-blue" @click="next">下一步</vxe-button>
                </div>
              </div>
              <div v-if="active === 2" style="height: 100%">
                  <Splitpanes style="height: calc(100% - 34px);">
                    <Pane size="70">
                      <div class="tableBox">
                        <vxe-table ref="reqDetailTableRef" :data="reqDetailList" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :show-footer="true" :footer-method="footerMethod" resizable show-overflow keep-source>
                          <vxe-column type="seq" width="60" fixed="left"></vxe-column>
                          <vxe-column field="feeCode" title="项目代号" ></vxe-column>
                          <vxe-column field="feeName" title="项目名称" min-width="120"></vxe-column>
                          <vxe-column field="people" title="总人数" >
                            <template #default="{ row }">
                              <el-link type="primary" :underline="false" @click="showPeople(row)">
                                <span>{{row.people}}</span>
                              </el-link>
                            </template>
                          </vxe-column>
                          <vxe-column field="price" title="单价" ></vxe-column>
                          <vxe-column field="amount" title="数量" ></vxe-column>
                          <vxe-column field="costs" title="金额" >
                          </vxe-column>
                        </vxe-table>
                      </div>
                    </Pane>
                    <Pane size="30">
                      <vxe-table ref="maintainDetailTableRef" class="mytable-scrollbar" border="inner" height="auto" align="center" :data="payWayList" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" :show-footer="true" :footer-method="feeFooterMethod" resizable show-overflow keep-source>
                        <vxe-column field="paytWay" title="支付编号" ></vxe-column>
                        <vxe-column field="paytWayName" title="支付名称" ></vxe-column>
                        <vxe-column field="costs" title="实收" :edit-render="{ autofocus: '.vxe-input--inner' }">
                          <template #default="{ row }">
                            {{ row.costs }}
                          </template>
                          <template #edit="{ row, rowIndex }">
                            <vxe-input v-model="row.costs" @blur="feeFooterMethod" type="float" placeholder="请输入两位小数"></vxe-input>
                          </template>
                        </vxe-column>
                      </vxe-table>
                    </Pane>
                  </Splitpanes>
                <div style="display: flex;align-items: center;justify-content: space-between;">
                  <div>
                    <el-descriptions :column="10" :labelStyle="{ width: '110px', background: '#fff', color: '#000', textAlign: 'center' }" :contentStyle="{ width: '130px' }" border>
                    </el-descriptions>
                  </div>
                  <div style="margin-right: 40px;">
                    <vxe-button :disabled="!checkChkShow" :loading="sloading" type="text" class="button-blue" icon="vxe-icon-save" content="结算"  @click="saveFinanceSettle"></vxe-button>
                    <vxe-button type="text" class="button-blue" @click="upper">上一步</vxe-button>
                  </div>
                </div>
              </div>
            </el-card>

            <vxe-modal v-model="isShowPeople" width="45vw" show-footer :mask="false">
              <template #title>
                <span class="text-bold">申请信息</span>
              </template>
              <template #default>
                <div class="tableBody" style="height: 600px">
                  <vxe-table ref="showPersonRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="peopleList" :loading="showPeopleTable"  :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                    <vxe-column title="序号" width="80">
                      <template #default="{ row, rowIndex, column }">
                        <span>{{ rowIndex + 1 }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="reqNo" title="条码号"></vxe-column>
                    <vxe-column field="patNo" title="病历号"></vxe-column>
                    <vxe-column field="patNa" title="患者姓名"></vxe-column>
                    <vxe-column field="reqPurpose" title="检测项目"></vxe-column>
                  </vxe-table>
                </div>
              </template>

              <template #footer>
                <vxe-button type="text" class="button-white margin-right" @click="cancelShowPersonEvent">关闭</vxe-button>
              </template>
            </vxe-modal>
          </el-container>
      </div>
  </div>
</template>
<script setup lang="ts">
import { Splitpanes, Pane } from 'splitpanes';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { IsEmpty, formatDateTime, autoIncrementNumber, notifyMessage, notifyType } from '@/utils/common';
import Template from "@/views/lab_sys/lab_bus/components/Template.vue";
import {isEmpty} from "lodash"; //返回组件
let { proxy }: any = getCurrentInstance();

let isShowPeople = ref(false);
let ploading = ref(false); //弹框表格数据加载状态
let showPeopleTable = ref(false); //弹框表格数据加载状态
let sloading = ref(false);
let checkChkShow = ref(true);
let active = ref(1);

let reqNoList: any = reactive([]); //弹框表格数据
let payWayList: any = reactive([]); //弹框表格数据
let peopleList: any = reactive([]); //弹框表格数据
const reqDetailList = reactive([]);
const footerData = ref([['总计金额', , ,]]);
const feeFooterData = ref([['实际金额', , ,]]);


let searchPersonForm = reactive({
  searchValue: '',
  startTime:'',
  endTime:''
});
let companyForm = reactive({
  id: null,
  settleStatus:'',
  companyCode:'',
  companyName:'',
  salesmanCode:'',
  salesmanName:'',
  alias:'',
  costs:0,
  realCosts:0
});

//暴露属性和方法
defineExpose({
  initPage
});
onMounted(() => {
  findPaytWayList();
});
function initPage(company: any) {
  reqNoList.length=0;
  reqDetailList.length=0;
  active.value=1;
  companyForm.companyCode=company.companyCode;
  companyForm.companyName=company.companyName;
  companyForm.salesmanCode=company.salesmanCode;
  companyForm.salesmanName=company.salesmanName;
  findReqNoList();
}

function cancelShowPersonEvent() {
  isShowPeople.value = false;
}
function showPeople(row :any) {
  findShowReqNoList(row.reqNo);
  isShowPeople.value = true;
}
function next() {
  active.value = 2
}
function upper() {
  active.value = 1
}

function findReqNoList() {
  reqNoList.length = 0; //放入数据前清空数据
  reqDetailList.length = 0; //放入数据前清空数据
  if (isEmpty(companyForm.companyCode)){
    VxeMessage('请选择送检单位', VxeNotifyType.error);
    return;
  }
  ploading.value = true;
  const url = '/lab/reqMain/findReqMainAndDetailList';
  proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: {
          seachValue: searchPersonForm.searchValue,
          state: '105',
          companyCode:companyForm.companyCode,
          salesmanCode:companyForm.salesmanCode,
          sTime: (isEmpty(searchPersonForm.startTime) ? null : searchPersonForm.startTime+' 00:00:00'),
          eTime: (isEmpty(searchPersonForm.endTime) ? null : searchPersonForm.endTime+' 23:59:59')
        }
      })
      .then((res: any) => {
        if (res.status.code == 1){
          reqNoList.length = 0; //放入数据前清空数据
          reqDetailList.length = 0; //放入数据前清空数据
          reqNoList.push(...res.data.reqList);
          reqDetailList.push(...res.data.reqdetai);
            //计算总价
            let cost=0;
            if (!IsEmpty(reqDetailList)) {
              for (const on of reqDetailList) {
                cost = cost + on.costs;
              }
            }
            companyForm.costs=cost;
        }
        ploading.value = false;
      })
      .catch((err: any) => {
        ploading.value = false;
        VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
      });
}

function findShowReqNoList(reqNos) {
  if (isEmpty(reqNos)){
    peopleList.length = 0; //放入数据前清空数据
    return;
  }
  showPeopleTable.value = true;
  peopleList.length = 0; //放入数据前清空数据
  const url = '/lab/reqMain/findMainList';
  proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: {
          reqNos: reqNos
        }
      })
      .then((res: any) => {
        peopleList.push(...res.data);
        showPeopleTable.value = false;
      })
      .catch((err: any) => {
        showPeopleTable.value = false;
        VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
      });
}

async function findPaytWayList() {
  payWayList.length = 0; //放入数据前清空数据
  let dictTreeTypeCodes: any = ['payWay'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const horizontalType = dictTreeTypeItems.data.find((item) => item.code === 'payWay');
  for (const item of horizontalType.detailDataList) {
    let mainStandard = {
      paytWay: item.code,
      paytWayName: item.name,
      costs: 0,
    };
    payWayList.push(mainStandard);
  }
}

function moneyAdd(num1, num2) {
  return (num1 * 100 + num2 * 100) / 100;
}


function saveFinanceSettle() {
  if (reqDetailList.length == 0){
    VxeMessage('没有收费项目', VxeNotifyType.error);
    return ;
  }
  if (IsEmpty(companyForm.realCosts) || companyForm.realCosts == 0){
    VxeMessage('请维护实际金额', VxeNotifyType.error);
    return ;
  }
  sloading.value = true;
    const url = '/lab/financeSettle/saveOrUpdateFinanceSettle';
    const supplier = {
      id: companyForm.id,
      companyCode:companyForm.companyCode,
      companyName:companyForm.companyName,
      salesmanCode:companyForm.salesmanCode,
      salesmanName:companyForm.salesmanName,
      settleType:'1',
      costs:companyForm.costs,
      realCosts:companyForm.realCosts,
      settleStatus:'10',
      settleDetailList: reqDetailList,
      payWayList: payWayList
    };
    proxy.$http
        .post(url, supplier)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('操作成功', VxeNotifyType.success);
            Object.assign(companyForm,res.data);
            checkChkShow.value=false;
          } else {
            VxeMessage('操作失败', VxeNotifyType.error);
          }
          sloading.value = false;
        })
        .catch((err: any) => {
          sloading.value = false;
          console.log(err);
          VxeMessage('操作失败', VxeNotifyType.error);
        });

}

function footerMethod() {
  let totalamount = 0;
  reqDetailList.forEach((element) => {
    totalamount += element.costs;
  });
  footerData.value = [['总计金额', '', '', '', '', '', totalamount + '']];
  return footerData.value;
}
function feeFooterMethod() {
  let totalamount = 0;
  payWayList.forEach((element) => {
    totalamount=moneyAdd(totalamount,element.costs);
  });
  feeFooterData.value = [['实际金额',  '', totalamount + '']];
  companyForm.realCosts=totalamount;
  return feeFooterData.value;
}
</script>
<style lang="scss">
#financeSettleEditDiv {
  height:100%;
  .vxe-cell--item{
    font-weight: bold;
  }

  .container{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    /*justify-content: center;*/
    align-items: center;
    background-color: $base-white;
    .el-card {
      .el-card__body {
      padding: 0;
      height: 100%;
    }
    }
  }
  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }
  .tableBox {
    height: 100%;
    background-color: $base-white;
  }

  .footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 5px 0;
    box-shadow: 8px 8px 15px #909399;
    background-color: $bg-gray;
    z-index: 9999;
    .el-form {
      transform: translateX(5%);
    }
    .el-form-item {
      margin-bottom: 0;
      margin-right: 12px;
    }
  }
}
</style>